<template>
  <div class="jq-table h-full flex-col">
    <div class="packageCardcontainer">
      <template v-for="boxContent in contentList" :key="boxContent?.title">
        <PackageCard class="card" :boxContent="boxContent" />
      </template>
    </div>
    <SearchForm :searchForm="searchForm"
      @handle-reset-form-datas="handleResetFormDatas"
      @handleSearch="handleSearch"
      @chanFormValue="chanFormValue"
    />
    <div class="page-card h-full" v-loading="loading">
      <JqTable :tableColumn="tableColumn" :tableButtons="tableButtons" :itemsButtons="itemsButtons" :data="tableData"
        :page="page" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" 
      >
      <template #serviceStatusEnumText>
          <el-table-column
            show-overflow-tooltip
            :min-width="80"
            prop="serviceStatusEnumText"
            label="状态"
            fit="true"
            show-header="true"
            align="left"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span :class="scope.row.serviceStatusEnum === 1 ? 'point1' : scope.row.serviceStatusEnum === 2 ? 'point3' : 'point4'"></span>
                <span>{{ scope.row['serviceStatusEnumText'] }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </JqTable>
      <!-- <AddOrUpdate ref="addOrUpdateRef" :dialogDatas="dialogDatas" @clear-form-datas="clearFormDatas"
        @handle-form-value="handleFormValue" @on-cancel="onCancel" @on-confirm="onConfirm" /> -->
        <AddOrUpdate v-if="showDialog" v-model:dialogVisible="showDialog" ref="addOrUpdateRef" :dialogDatas="dialogDatas"
        @update-list="updateList" />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'User' });//用户管理
import { reactive, ref, onBeforeMount, computed, watch } from 'vue';
import { useTable } from '@/hooks/useTable';
import { userListRequest, userStatisticsRequest, userAddUserRequest,exportRequest } from '@/api/user/index';
// import type { IUserItem } from '@/api/user/type';
import { orgOptionsRequest, healthDoctorOptionsRequest } from '@/api/common/index';
import { JqTable } from '@/components/Table/index';
import { useRouteStore } from '@/store';
// import AddOrUpdate from '@/components/Add-or-update/src/AddOrUpdate.vue';
import { AddOrUpdate } from './components';
import { PackageCard } from '@/components/PackageCard/index';
import type { FormInstance } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { enumListRequest } from '@/api/common';
import { tr } from 'element-plus/es/locale';
const router = useRouter();
const showDialog = ref(false)
const routeStore = useRouteStore();
const currentMenudatas = computed(() => routeStore.currentMenudatas);//路由btn
let orgIdDatas = reactive([]);//归属组织下拉
let healthDoctorOptions = reactive([]);
const addOrUpdateRef = ref();
let searchFormParams = reactive<any>({});

let  searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '用户查询',
    placeholder: '请输入用户查询',
    eName: 'searchWords'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织',
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'selectson',
    value: '',
    label: '归属健康顾问',
    options: () => {
      return healthDoctorOptions;
    },
    eName: 'adminUserId'
  },
  {
    type: 'select',
    value: '',
    label: '状态',
    options: () => {
      return mealStatusEnumList
    },
    eName: 'serviceStatus'
  },
  {
    type: 'date',
    value: '',
    label: '创建时间',
    eName: 'createTime'
  }
]);

const tableColumn = reactive([
  { label: '用户姓名', prop: 'name',minWidth: '80' },
  { label: '归属组织机构', prop: 'orgName',minWidth: '120' },
  { label: '归属健康顾问', prop: 'healthDoctorName',minWidth: '120' },
  { label: '创建时间', prop: 'createTime',minWidth: '170' },
  { label: '最后一次检测时间', prop: 'lastCheckTime',minWidth: '170' },
  { label: '年龄', prop: 'age',minWidth: '80' },
  { label: '手机号', prop: 'phone',minWidth: '140' },
  { label: '状态', prop: 'serviceStatusEnumText',minWidth: '80' ,slot: true },
  { label: '当前机构检测次数', prop: 'checkTimes',minWidth: '160' }
]);
let tableButtons = reactive([
  {
    id: 34,
    type: 'primary',
    label: '添加',
    perms: 'user:btn:create',
    onClick: () => {
      showDialog.value = true
      dialogDatas = {
        title: '新增',
        type: 'add',
        datas: dialogForConfigDatas
      };
    }
  },
  {
    id: 36,
    type: '',
    label: '导出',
    perms: 'user:btn:export',
    onClick: async (row:any) => {
      const params=Object.assign({},searchFormParams,{pageNum: page.page, pageSize: page.pageSize })
      const data: any =  await exportRequest(params)
      window.open(data.data);
    }
  }
]);

let itemsButtons = reactive([
  {
    id: 35,
    type: 'primary',
    label: '查看',
    perms: 'user:btn:view',
    onClick: (rowData: any) => {
      router.push({ path: '/user/deatils', query: { id: rowData.id } });
    }
  }
  
]);
const contentList = reactive([
  {
    title: '本月新增用户',
    number: '',
    bgUrl: 'Bg.png',
    iconUrl: 'Icon.png'
  },
  {
    title: '用户总数',
    number: '',
    bgUrl: 'Bg2.png',
    iconUrl: 'Icon2.png'
  },
  {
    title: '3个月活跃用户',
    number: '',
    bgUrl: 'Bg3.png',
    iconUrl: 'Icon3.png'
  },
  {
    title: '6个月活跃用户',
    number: '',
    bgUrl: 'Bg4.png',
    iconUrl: 'Icon4.png'
  },
  {
    title: '待激活的用户',
    number: '',
    bgUrl: 'Bg5.png',
    iconUrl: 'Icon5.png'
  }
]);
const onAddOrUpdate = (data?: Recordable) => {
  addOrUpdateRef.value.handleDialog(true);
  addOrUpdateRef.value.init(data);
};
let dialogDatas = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: userListRequest,
    params: ()=>searchFormParams
  });

const chanFormValue=(formParamsDatats:{})=>{
  searchFormParams=formParamsDatats
}
// 表单数据
let dialogForConfigDatas = reactive([
  {
    type: 'input3',
    value: '',
    label: '手机号码',
    required: true,
    placeholder: '请输入手机号码',
    eName: 'phone'
  },
  {
    type: 'input4',
    value: '',
    label: '用户姓名',
    required: true,
    placeholder: '请输入用户姓名',
    eName: 'name'
  },

  {
    type: 'select',
    value: '',
    label: '归属组织机构',
    required: true,
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },

  {
    type: 'select',
    value: '',
    label: '归属健康顾问',
    required: true,
    options: () => {
      return jkgwOptions;
    },
    eName: 'healthDoctorId'
  },
  {
    type: 'select',
    value: '',
    label: '性别',
    required: true,
    options: () => [
      { id: '1', name: '男' },
      { id: '2', name: '女' },
    ],
    eName: 'gender'
  },
  {
    type: 'date',
    value: '',
    label: '出生日期',
    required: true,
    placeholder: '请输入出生日期',
    eName: 'birthday'
  },
  {
    type: 'input-number',
    value: '',
    label: '身高（CM）',
    required: true,
    eName: 'height'
  },
  {
    type: 'input-number',
    value: '',
    label: '体重（kg）',
    required: true,
    eName: 'weight'
  }
]);
// 数据筛选
const handleSearch = ((searchFormParamsDatats:any) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  getList();
});
watch(() => dialogForConfigDatas[2].value, (newVal, oldVal) => {
  dialogForConfigDatas[3].value = '';
  getjkgwOptions(newVal)
})
// 筛选数据监听(组织机构)
watch(() => searchForm[1].value, (newVal, oldVal) => {
  searchForm[2].value = '';
  getHealthDoctorOptions(newVal)
})
// 归属健康顾问
let jkgwOptions = reactive([])
const getjkgwOptions = async (newVal: any) => {
  if (newVal) {
    const data: any = await healthDoctorOptionsRequest({ orgId: newVal });
    jkgwOptions = data.data;
  } else {
    jkgwOptions = []
  }
};

// 组织下拉
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
};
// 健康顾问下拉
const getHealthDoctorOptions = async (id: any) => {
  if (id && id !== null) {
    const data: any = await healthDoctorOptionsRequest({ orgId: id });
    healthDoctorOptions = data.data;
  } else {
    healthDoctorOptions = []
  }
};
// banner 数量统计
const getUserStatistics = async () => {
  const data: any = await userStatisticsRequest({});
  let currentData = data.data;
  contentList[0].number = currentData.currMtIncr;
  contentList[1].number = currentData.total;
  contentList[2].number = currentData.within3MtsActive;
  contentList[3].number = currentData.within6MtsActive;
  contentList[4].number = currentData.inactive;
};
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
const updateList = () => {
  getList();
  getUserStatistics();
  showDialog.value = false
}
/*清除表单值 */
// const clearFormDatas = () => {
//   dialogForConfigDatas = dialogForConfigDatas.map((item) => {
//     if (item.value) {
//       item.value = '';
//     }
//     return item;
//   });
// };
// const handleFormValue = (data: any) => { };
// const onCancel = () => {//取消
//   clearFormDatas();
//   addOrUpdateRef.value.handleDialog(false);
// };
/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams={}
  searchForm = searchForm.map((item) => {
    if (item.value) {
      item.value = '';
    }
    return item;
  });
 getList();

};
// const onConfirm = async (data: {}, type: any) => {//确定
//   await addUserDatas(data);
//   addOrUpdateRef.value.handleDialog(false);
//   clearFormDatas();
//   getList();
// };
/*添加*/
const addUserDatas = async (datas: {}) => {
  const data: any = await userAddUserRequest(datas);
};
// 状态下拉
let mealStatusEnumList = reactive([])
const getMealStatusEnum = async () => {
  const data: any = await enumListRequest({ enumName: 'ServiceStatusEnum' });
  mealStatusEnumList = data.data;
};
onBeforeMount(() => {
  getUserStatistics();
  
  if(!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
})
getMealStatusEnum();
getOrgOptionsDatas();
getHealthDoctorOptions(null);
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;

  >.card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom: 10px;

    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
